import {
  C0LUMNS,
  DELIVERY_ORDER_C0LUMNS,
  RECEIVE_C0LUMNS,
  RECEIVE_COORDINATION,
  SHIPPING_INFORMATION,
  PAY_INFO,
  CANCEL_C0LUMNS,
  STOCK_TYPE,
  SERIAL,
  ACCESSORIES_COLUMNS
} from './index.const';
import ElEditable from '@components/el-editable';
import { numMulti } from '~/common'
import {
  queryOrderInfo,
  stockBatchList,
  orderProductList,
  getOrderDeliverList,
  findPaymentByOrderId,
  getOrderDeliverDetailList,
  findOrderStatus,
  getOrderLogistics,
  orderCancelProductList,
  findStockStatus,
  orderGetAppendInfo,
  returnStatus,
  findProductSnInfo,
  pageProductDetailList,
  queryOrderDetailProductList
} from '@api/m_mall_web_v1.js';

import step from '~/modules/step';
import TableUpload from '~/modules/table-upload';
import { setProductPrice } from '~/common'
export default {
  components: {
    ElEditable,
    step,
    TableUpload
  },
  inject: ['apiMMallWeb'],
  data() {
    return {
      // text: "(去应付账单管理支付)",
      // timeOut: '00:00:00',
      // showTimeOut: true,
      serialPage: 0, // 序列号页数
      serialPageSize: 20, //序列号条数
      payloadSerialList: [],
      currentPage: 1,
      pageSize: 20,
      receivCurrentPage: 1,
      receivPageSize: 20,
      receivData: {},
      rowData: {},
      receivDataLoading: false,
      tableLoading: false,
      payload: {},
      dialogVisible: false,
      PAY_INFO, //支付信息
      C0LUMNS,
      CANCEL_C0LUMNS,
      SERIAL,
      RECEIVE_COORDINATION, //收货信息表头
      RECEIVE_C0LUMNS, //收货详情表头
      DELIVERY_ORDER_C0LUMNS, //出库单表头
      SHIPPING_INFORMATION, //配送信息表头
      STOCK_TYPE,
      logisticsData: [],
      orderDetail: {},
      orderId: '',
      orderCode: '',
      orderDetailId: '',
      orderIdReturn: '',
      orderCodeReturn: '',
      orderIdExchange: '',
      orderCodeExchange: '',
      busModel: 1,
      orderType: 1,
      activeName: 'first',
      order_tab: [],
      stepData: [],
      stepData_offline: [],
      stepStr_offline: [],
      stockBatchData: [],
      supplierVo: {},
      addressResDto: {},
      orderAppendPOS: [],
      payDetailData: [],
      returnStutas: '',       //退货状态
      exchangeStutas: '',     //换货状态
      //取消产品列表
      cancelTableLoading: false,
      cancelPayload: {},
      cancelContent: [],
      cancelCurrentPage: 1,
      cancelPageSize: 20,
      productPageSize: 20,
      productPage: 1,
      ACCESSORIES_COLUMNS,
      payloadProducts: {}, // 详情页产品信息
      serialCount: 0
    };
  },
  created() {
    this.orderId = this.$route.query.id;
    this.orderCode = this.$route.query.orderCode
    this.orderDetailId = this.$route.query.orderDetailId
    // this.setTime()
    //获取步骤条数据
    this.getStepList()
  
    // 获取支付信息
    this.getPayment()
    // 获取产品信息
    this.getProducts()
    //根据id获取列表详情
    this.$axios.$post(queryOrderInfo, {
      orderId: this.orderId
    }).then(res => {
      if (res.code === '0' && res.payload) {
        this.supplierVo = res.payload.supplierVo
        this.addressResDto = res.payload.addressResDto
        this.orderAppendPOS = res.payload.orderAppendPOS
        this.orderDetail = {
          ...res.payload
        }
        this.orderIdReturn = res.payload.orderIdReturn
        this.orderCodeReturn = res.payload.orderCodeReturn
        this.orderIdExchange = res.payload.orderIdExchange
        this.orderCodeExchange = res.payload.orderCodeExchange
        this.orderDetailId = res.payload.orderDetailId
        this.orderDetail.commonFilePOList = res.payload.commonFilePOList
        this.orderCode = res.payload.orderCode || ''
        this.getAppendInfo(res.payload.contractVo)
        this.getCancelList(res.payload.orderDetailId)
        // 获取序列号信息
        this.findProductSnInfo()
      }
    })

    //库存配位
    this.$axios.$post(stockBatchList, {
      orderId: this.orderId,
      page: 1,
      pageSize: 99999
    }).then(res => {
      if (res.code === '0' && res.payload.content) {
        this.stockBatchData = res.payload.content
      }
    })
  },
  async mounted() {
    await this.getReturnStatus()
    let arr = [];
    if(this.returnStutas === 1){
      arr.push({type: 'primary', disabled: true, val: '退货中', handle: this.returning})
    }
    else if(this.returnStutas === 2){
      arr.push({type: 'primary', val: '申请退货', handle: this.applyForReturn})
    }
    if(this.exchangeStutas === 1){
      arr.push({type: 'primary', disabled: true, val: '换货中', handle: this.exchangeing})
    }
    else if(this.exchangeStutas === 2){
      arr.push({type: 'primary', val: '申请换货', handle: this.applyForExchange})
    }
    let btn = {
      type: 'btn',
      arr
    }
    this.$store.commit('changeLayoutHandle', btn)
  },
  methods: {
    //退货/换货按钮展示
    getReturnStatus() {
      let params = {
        orderCode:this.orderCode
      }
     return this.$axios.$post(returnStatus, params)
      .then(res => {
        if(res.code === '0') {
          this.returnStutas = res.payload.returnStutas
          console.log(this.returnStutas)
          this.exchangeStutas = res.payload.exchangeStutas
          console.log(this.exchangeStutas)
        }
        return Promise.resolve(res)
      })
    },
    getAppendInfo(obj) {
      this.$axios.$post(orderGetAppendInfo, {
        productLineCode: obj.productLineCode,
        vendorNum: obj.supplierCode,
        busModel: '11',
        page: 1,
        pageSize: 9999,
      }).then(res => {
        if (res.code === '0' && res.payload) {
          this.orderAppendPOS.forEach(item => {
            res.payload.forEach(it => {
              if (item.attributeName === it.attributeName) {
                let list = it.valueRange ? JSON.parse(it.valueRange) : []
                list.forEach(val => {
                  if (val.value === item.attributeValue) {
                    item.attributeValue = val.label
                  }
                })
              }
            })
          })
        }
      })
    },
    // setTime() {
    //   const endTime = new Date("2020/07/21 11:09:00").getTime();
    //   const staTime = new Date().getTime()
    //   if (endTime > staTime) {
    //     let that = this
    //     let timer = setInterval(function () {
    //       let time = new Date().getTime()
    //       let time_distance = endTime - time
    //       // 时
    //       var int_hour = Math.floor(time_distance / 3600000);
    //       time_distance -= int_hour * 3600000;
    //       // 分
    //       var int_minute = Math.floor(time_distance / 60000);
    //       time_distance -= int_minute * 60000;
    //       // 秒
    //       var int_second = Math.floor(time_distance / 1000);
    //       // 时分秒为单数时、前面加零
    //       if (int_hour < 10) {
    //         int_hour = "0" + int_hour;
    //       }
    //       if (int_minute < 10) {
    //         int_minute = "0" + int_minute;
    //       }
    //       if (int_second < 10) {
    //         int_second = "0" + int_second;
    //       }
    //       if (int_hour == 0 && int_minute == 0 && int_second == 0) {
    //         that.timeOut = "00:00:00"
    //         clearInterval(timer)
    //         that.text = '已超时，请重新下单'
    //       } else {
    //         that.timeOut = `${int_hour}:${int_minute}:${int_second}`;
    //       }
    //     }, 1000)
    //   } else {
    //     this.text = '(已超时，请重新下单)'
    //   }
    // },
    getStepList() {
      this.$axios.$post(findOrderStatus, {
        orderId: this.orderId
      }).then(res => {
        if (res.code === '0' && res.payload.orderStatusInfoVO) {
          this.stepData = res.payload.orderStatusInfoVO
        }
      });
      this.$axios.$post(findStockStatus, {
        orderId: this.orderId
      }).then(res => {
        if (res.code === '0' && res.payload) {
          let data = res.payload.orderStatusInfoVO
          let arr = []
          let newArr = []
          data.map(item => {
            if (Number(item.lineNum) === 1) {
              arr.push(item)
            } else {
              newArr.push(item)
            }
          })
          arr.sort(function (a, b) {
            return a.orderStatus - b.orderStatus
          });
          this.stepData_offline.push(arr)
          if (newArr.length) {
            let num = newArr.length / 2
            for (let i = 1; i <= num; i++) {
              let itemArr = []
              newArr.map(item => {
                if (Number(item.lineNum) === i + 1) {
                  itemArr.push(item)
                }
              })
              itemArr.sort(function (a, b) {
                return a.orderStatus - b.orderStatus
              });
              this.stepData_offline.push(itemArr)
            }
          }
          console.log(this.stepData_offline, 2212121)
          let str = res.payload.remark ? res.payload.remark.split(',') : []
          str.map(item => {
            if (this.STOCK_TYPE[item]) {
              this.stepStr_offline.push(this.STOCK_TYPE[item])
            }
          })
        }
      })
    },
    //添加高亮
    tableRowClassName({
      row
    }) {
      if (row.confirmCount) {
        if (row.productCount > row.confirmCount) {
          return 'bgHeight';
        }
      }
    },
    //订单详情采购产品分页列表分页器
    reloadProductData(val) {
      this.productPage = val.number
      this.productPageSize = val.size
      this.getProducts()
    },
    // cancelReloadProductData() {
    //   this.cancelCurrentPage = val.number
    //   this.cancelPageSize = val.size
    //   this.getCancelList()
    // },
    // 序列号分页
    findProductSnInfoReload(val) {
      this.serialPage = val.number
      this.serialPageSize = val.size
      this.findProductSnInfo()
    },
    // 支付分页
    getCancelList(orderDetailId) {
      this.cancelTableLoading = true
      this.$axios.$post(orderCancelProductList, {
        orderDetailId: this.orderDetailId,
        page: this.cancelCurrentPage,
        pageSize: this.cancelPageSize
      }).then(res => {
        if (res.code === '0' && res.payload.content) {
          this.cancelPayload = res.payload;
          this.cancelContent = res.payload.content;
        }
        this.cancelTableLoading = false
      })
    },
    //底部tab切换调用不同接口
    // handleClick(tab, event) {
    //   if (tab.name === "fourth") {
    //     this.getOrderDeliverList()
    //   }
    //   if (tab.name === 'second') {
    //     this.getPayment()
    //   }
    //   if (tab.name === 'third') {
    //     this.getLogistics()
    //   }
    // },
    // 支付信息
    getPayment() {
      this.$axios.$get(`${findPaymentByOrderId}?orderId=${this.orderId}`).then(res => {
        if (res.code === '0' && res.payload) {
          this.payDetailData = [res.payload]
        }
      })
    },
    //配送信息
    getLogistics() {
      this.$axios.$post(getOrderLogistics, {
        orderCode: this.orderDetail.orderCode
      }).then(res => {
        if (res.code === '0' && res.payload) {
          this.logisticsData = res.payload
        }
      })
    },
    //收货信息列表
    getOrderDeliverList() {
      this.$axios.$get(`${getOrderDeliverList}?orderCode=${this.orderDetail.orderCode}`)
        .then(res => {
          if (res.code === '0' && res.payload) {
            this.order_tab = res.payload
          }
        })
    },
    showLog(row) {
      this.dialogVisible = true;
      this.rowData = row
      this.getReceivList()
    },
    //收货信息-详情列表分页器
    reloadReceiv(val) {
      this.receivCurrentPage = val.number
      this.receivPageSize = val.size
      this.getReceivList()
    },
    //收货信息-详情列表
    getReceivList() {
      this.receivDataLoading = true
      this.$axios.$post(getOrderDeliverDetailList, {
        deliverCode: this.rowData.deliverCode,
        page: this.receivCurrentPage,
        pageSize: this.receivPageSize
      }).then(res => {
        if (res.code === '0' && res.payload) {
          this.receivData = res.payload
        }
        this.receivDataLoading = false
      })
    },
    //退货中页面跳转
    returning() {
      this.$router.push({
        path: '/after-sale/order-management/returnDetails',
        query: {
          orderId: this.orderIdReturn,
          orderCode: this.orderCodeReturn
        }
      })
    },
    //申请退货页面跳转
    applyForReturn() {
      this.$router.push({
        path: '/purchase-order/consign/list/return',
        query: {
          orderId: this.orderId,
          orderType: this.orderType
        }
      })
    },
    //换货中页面跳转
    exchangeing() {
      this.$router.push({
        path: '/after-sale/order-management/returnDetails',
        query: {
          orderId: this.orderIdExchange,
          orderCode: this.orderCodeExchange
        }
      })
    },
    //申请换货页面跳转
    applyForExchange() {
      this.$router.push({
        path: '/purchase-order/consign/list/exchange',
        query: {
          orderId: this.orderId,
          orderType: this.orderType
        }
      })
    },
    // 获取序列号
    findProductSnInfo  () {
      this.$axios.$post(findProductSnInfo , {
        orderCode: this.orderCode,
        page: this.serialPage,
        pageSize: this.serialPageSize
      }).then(res => {
        if (res.code === '0' && res.payload) {
          let serialCountAdd = 0;
          (res.payload && res.payload.content || []).map( s => {
            serialCountAdd = numMulti(serialCountAdd, 10000) + numMulti(s.productCount, 10000)
            serialCountAdd = Math.floor (serialCountAdd)/ 10000
          })
          this.serialCount = serialCountAdd
          this.payloadSerialList = res.payload
        }
      })
    },
    getProducts () {
      this.$axios.$post(queryOrderDetailProductList, {
        orderId: this.orderId,
        orderDetailId: this.orderDetailId,
        page: this.productPage,
        pageSize: this.productPageSize
      }).then(res => {
        if (res.code === '0' && res.payload) {
          this.payloadProducts = res.payload
        }
      })
    }
  }
};